package com.example.blog.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Question LoginInterceptor 登录拦截器 登录校验
 * @Date 2023/1/7 11:02
 * @Solution
 */
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session!=null && session.getAttribute("user")!=null) {
            return true;
        } else {
            log.error("用户无权限访问");
            response.setStatus(401);
            return false;
        }
    }
}
